package com.xc.smart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xc.smart.entity.LoginUser;
import com.xc.smart.entity.User;
import com.xc.smart.exception.RRException;
import com.xc.smart.jwt.JWTService;
import com.xc.smart.mapper.UserMapper;
import com.xc.smart.service.UserService;
import com.xc.smart.utlis.DateUtilss;
import com.xc.smart.utlis.R;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author mtl
 * 2021/6/8
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {

    @Autowired
    UserMapper userMapper;


    @Autowired
    JWTService jwtService;

    @Override
    public User selectById(Integer id) {
        User user = userMapper.selectById(id);
        return user;
    }

    @Override
    public User selectByName(String name) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq(User.COL_USERNAME, name).last("limit 1"));
        return user;
    }


    @Override
    public R login(String username, String password, HttpServletRequest request) {
        User user = queryByName(username);
        if(user==null){
            return R.error("该用户不存在");
        }
        //密码错误DigestUtils.sha256Hex()
        if(StringUtils.isEmpty(user.getPassword()) || !user.getPassword().equals(DigestUtils.sha256Hex(password))){
            throw new RRException("密码错误",205);
        }
        LoginUser loginUser = new LoginUser();
        loginUser.setIpaddr(request.getRemoteAddr());
        loginUser.setBrowser(request.getLocalName());
        loginUser.setOs(request.getServerName());
        loginUser.setUser(user);
        String token = jwtService.createToken(loginUser);

        return R.ok().put("Authorization",token);

    }

    @Override
    public User queryByName(String username) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq(User.COL_USERNAME, username));
        return user;
    }


}
